<template>
  <div class="content">
    <el-dialog title="用户信息" :visible.sync="dialogVisible" width="450px" @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" style="width: 100%">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name" style="width: 300px"></el-input>
          <el-alert title="初始密码为123456"  :closable="false"  type="info" show-icon
                    style="line-height: 12px"></el-alert>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            style="width: 100%"
            v-model="form.birthday"
            type="date"
            placeholder="请选择生日日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="电话号码" prop="tel">
          <el-input v-model="form.tel"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input v-model="form.idCard"></el-input>
        </el-form-item>
        <el-form-item label="照片" prop="photo">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            action="http://localhost:8085/files/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.photo" :src="form.photo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdate(form)" v-if="this.form.id">更新</el-button>
          <el-button type="primary" @click="handleSave(form)" v-else>添加</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="Excel导入老师" :visible.sync="dialogSaveVisible" width="650px" @close="closeDialog2">
      <el-form :inline="true"  class="demo-form-inline" >
        <el-form-item style="margin-left: 50%;position: relative;left: -120px">
          <el-upload
            ref="upload2"
            class="upload-demo"
            accept=".xlsx,.xls"
            :auto-upload="false"
            action=""
            :limit="1"
            :on-exceed="handleExceed"
            :http-request="httpRequest"
          >
            <template #trigger>
              <el-tooltip content="仅限文件格式为.xls,.xlsx" placement="top" effect="light">
                <el-button type="primary">选择文件</el-button>
              </el-tooltip>
            </template>
            <el-button style="margin-left: 10px"
                       type="success"
                       @click="submitUpload"
            >立即导入<i class="el-icon-upload el-icon-right"></i>
            </el-button>
          </el-upload>
        </el-form-item>
        <el-alert title="字段依次:姓名、性别(男/女)、生日(yyyy-MM-dd)、手机号码、电子邮箱、地址、身份证" type="warning" close-text="知道了" show-icon
                  style="line-height: 12px;"></el-alert>
      </el-form>
    </el-dialog>

    <el-form :inline="true"  class="demo-form-inline">
      <el-form-item>
        <el-input  placeholder="教师名" v-model="search.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input  placeholder="工号" v-model="search.schoolno"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button  @click="getList(search.name,search.schoolno)">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dialogVisible = true">新添教师</el-button>
      </el-form-item>
      <el-form-item>
        <el-form-item>
          <el-popconfirm title="这是确定批量删除吗？" @onConfirm="handleDel(null)">
            <template #reference>
              <el-button type="danger" slot="reference" :disabled="delBtlStatu">批量删除</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dialogSaveVisible = true">Excel导入老师</el-button>
      </el-form-item>
<!--      <el-form-item>-->
<!--        <el-upload-->
<!--          ref="upload2"-->
<!--          class="upload-demo"-->
<!--          accept=".xlsx,.xls"-->
<!--          :auto-upload="false"-->
<!--          action=""-->
<!--          :limit="1"-->
<!--          :on-exceed="handleExceed"-->
<!--          :http-request="httpRequest"-->
<!--        >-->
<!--          <template #trigger>-->
<!--            <el-tooltip content="仅限文件格式为.xls,.xlsx" placement="top" effect="light">-->
<!--              <el-button type="primary">选择文件</el-button>-->
<!--            </el-tooltip>-->
<!--          </template>-->
<!--          <el-button style="margin-left: 10px"-->
<!--                     type="success"-->
<!--                     @click="submitUpload"-->
<!--          >立即导入<i class="el-icon-upload el-icon-right"></i>-->
<!--          </el-button>-->
<!--        </el-upload>-->
<!--      </el-form-item>-->
    </el-form>
    <el-table
      ref="multipleTable"
      :data="table"
      border
      stripe
      v-loading="loading"
      element-loading-text="拼命加载中..."
      element-loading-background="rgba(255, 255, 255, 0.7)"
      style="width: 100%"
      @row-click="toggleSelection"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column
        label="照片"
      >
        <template slot-scope="scope">

          <el-avatar shape="square" v-if="scope.row.photo==null||scope.row.photo===''" size="medium" :src="squareUrl"></el-avatar>
          <el-avatar shape="square" v-else size="medium" :src="scope.row.photo"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="员工名称"
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="schoolno"
        label="员工号"
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="sex"
        label="性别"
        sortable
      ><template #default="scope">
        <span v-if="scope.row.sex===1">男</span>
        <span v-if="scope.row.sex===2">女</span>
      </template>
      </el-table-column>
      <el-table-column
        prop="birthday"
        label="生日"
        type="date"
        sortable
      >
      </el-table-column>
      <el-table-column
        prop="tel"
        label="电话号码">
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
      <el-table-column
        prop="idCard"
        label="身份证">
      </el-table-column>
      <el-table-column
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-button  type="text" size="small" @click="handelEdit(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="这是确定删除吗？" @onConfirm="handleDel(scope.row.id)">
            <el-button  type="text" slot="reference" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="current"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import {getTeacherList,del,update,save,upload} from '@/api/sysUser/teacher'

export default {
  name: 'StudentClass',
  data() {
    //电子邮箱格式校验方法
    var checkEmail=(rule,value,callback)=>{
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      //头像
      //默认头像
      squareUrl:"https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
      loading: true,
      delBtlStatu: true,
      // 分页用到的属性
      total: 0,
      current: 1,
      size: 10,
      //搜索
      search:{
        name:"",
        schoolno:"",
      },
      //表格
      table:[],
      //对话框
      dialogVisible: false,
      dialogSaveVisible: false,
      //表单
      form:{
        id:null,
        schoolno: "",
        name:'',
        sex:'',
        birthday:'',
        tel:'',
        email:'',
        address:'',
        idCard:'',
        photo:'',
      },
      //校验
      rules: {
        name: [
          {required: true, message: '请输入用户姓名', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        tel: [
          { required: true,min: 11, max: 11, message: '手机号码输入有误', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱格式有误', trigger: 'blur',validator:checkEmail}
        ],
        address:[{
          required:true,  message: '请输入地址', trigger: 'blur'}
        ],
        idCard:[{
          min:18, max:18, required:true,  message: '身份证格式有误', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getList()
    // this.getGrade()
  },
  methods: {

    toggleSelection(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    // 触发事件为有复选框发生变化，会传递所有勾选的行数据对象数组
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //设置批量删除的按钮的可用/不可用
      this.delBtlStatu = val.length == 0
    },
    //这里是分页
    handleSizeChange(val) {
      this.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getList()
    },
    getList(){
      getTeacherList(this.search.name,this.search.schoolno,this.current,this.size).then(res => {
        this.table = res.data.data.records
        this.size = res.data.data.size
        this.total = res.data.data.total
        this.current = res.data.data.current
        this.loading=false
      })
    },
    //上传头像
    handleAvatarSuccess(res,file){
      this.form.photo=res.data
      this.$message({
        message:'你已上传成功',
        type:'success'
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    closeDialog(){
      this.form= { name:'', sex:'', birthday:'',tel:'',email:'',address:'',idCard:''}
      this.$refs.form.resetFields();
      this.dialogVisible = false

    },
    closeDialog2(){

      this.$refs.upload2.clearFiles()
      this.dialogVisible = false

    },
    handleSave(){
      this.$refs.form.validate(valid => {
        if (valid) {
          save(this.form).then(res=>{
            this.dialogVisible = false
            this.$message({
              message: res.data.msg,
              type: 'success'
            })
            this.getList()
          })
        } else {
          return false;
        }
      });
    },
    handleUpdate(){
      this.$refs.form.validate((valid) =>{
        if (valid) {
          update(this.form).then(res=>{
            this.dialogVisible = false
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
            this.getList()
          })
        } else {
          return false;
        }
      });
    },
    handelEdit(row){
      this.dialogVisible = true
      this.$nextTick(() => {
        this.form = JSON.parse(JSON.stringify(row))
      })
    },
    handleDel(id){
      console.log('删除')
      var ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      del(ids).then(res=>{
        this.$message({
          message:res.data.msg,
          type:'success'
        });
        this.getList();
      })
    },
    //批量导入老师
    handleExceed(file,fileList){
      this.$message.warning('每次只能选择一个文件');
    },
    httpRequest(param){
      let excelFileObj=param.file
      let form=new FormData()
      form.set('excel',excelFileObj)
      upload(form).then(res=>{
        this.$message({
          showClose:true,
          message:'恭喜你，操作成功',
          type:'success',
        });
        this.getList()
        this.$refs.upload2.clearFiles()
      })
    },
    submitUpload(){
      this.$refs.upload2.submit()
    },
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
